package com.example.zz.example.fileproviderandshare;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.zz.example.R;
import com.zz.fileproviderlibrary.fileprovider.UriUtils;
import com.zz.fileproviderlibrary.fileshare.FileUtil;
import com.zz.fileproviderlibrary.fileshare.ShareBySystem;
import com.zz.fileproviderlibrary.fileshare.ShareContentType;

import java.io.File;

public class FileProviderAndShareActivity extends AppCompatActivity {
    private static final int FILE_SELECT_CODE = 100;
    private static final int PIC_SELECT_CODE = 200;
    private static final int AUDIO_SELECT_CODE = 300;
    private static final int VIDEO_SELECT_CODE = 400;
    private static final int REQUEST_SHARE_FILE_CODE = 120;
    private static final int REQUEST_WRITE_STORAGE_PERMISSION = 121;

    private EditText editText;
    private EditText sharePath;
    private EditText sharePathType;
    private Button pathShareButton;
    private Uri shareFileUrl = null;

    /**
     * 最核心方法，文件绝对地址与uri之间的转化。
     * 7.0之前可以直接通过Uri uri = Uri.fromFile(new File(external_filePath));进行转化，不管是私有目录还是公共目录
     * external_filePath="/storage/emulated/0/fish/myTxt.txt"
     * 构造为uri 后uriString="file:///storage/emulated/0/fish/myTxt.txt"
     * <p>
     * 7.0之后，无法直接进行转化，因为转化后的uri含有全路径，不安全
     * <p>
     * android文件管理方式
     * 1、FileProvider，管理android所有文件，包括内部存储、外部私有存储、外部共有存储
     * 2、ContentResolver + MediaStore，管理媒体文件，文件存储在外部共有存储时，系统帮忙自动写入ContentResolver的数据库
     * <p>
     * 下面的FileUtil.getFileUri获取uri的方案是，7.0之前通过Uri.fromFie的形式获取，7.0之后，通过ContentResolver + MediaStore获取
     * android9及一下的设备适配没有问题，android10/11版本时，文件存入外部私有存储，无法获取到uri，存储到外部共有存储时可以获取到
     * <p>
     * UriUtils.getUri获取uri方案是，7.0之前通过Uri.fromFie的形式获取，7.0之后，通过FileProvider获取
     * android10/11 经过FileProvider配置的目录都可以获取到，包括内存存储、外部私有存储、外部共有存储
     * <p>
     * 参考：Android-10、11-存储完全适配  等
     * https://www.jianshu.com/p/62824be8141e
     *
     * @param path
     * @return
     */
    private Uri getUriWithAbsolutePath(String path) {
//        FileUtil.getFileUri(FileProviderAndShareActivity.this,ShareContentType.TEXT, new File(path));
        Uri fileUri = UriUtils.getUri(FileProviderAndShareActivity.this, path);
        return fileUri;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_provider_and_share);
        editText = findViewById(R.id.tv_share_file_url);
        editText = findViewById(R.id.tv_share_file_url);
        sharePath = findViewById(R.id.tv_share_path);
        sharePathType = findViewById(R.id.tv_share_path_type);
        pathShareButton = findViewById(R.id.bt_share_by_path);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE_PERMISSION);
            } else {
                Toast.makeText(this, "缺少文件读写权限，可能会造成无法分享文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE_STORAGE_PERMISSION) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "缺少文件读写权限，可能会造成无法分享文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void handlerShare(View view) {
        switch (view.getId()) {
            case R.id.bt_share_text:
                String s = editText.getText().toString();
                new ShareBySystem.Builder(this)
                        .setContentType(ShareContentType.TEXT)
                        .setTextContent(s)
                        .setTitle("Share Text")
                        .build()
                        .shareBySystem();
                break;
            case R.id.bt_share_by_path:
                String path = sharePath.getText().toString().trim();
                String type = sharePathType.getText().toString().trim();

                Uri fileUri = getUriWithAbsolutePath(path);

                new ShareBySystem.Builder(this)
                        .setContentType(type)
                        .setShareFileUri(fileUri)
                        .setTitle("Share File")
                        .build()
                        .shareBySystem();
                break;
            case R.id.bt_share_image:
                openFileChooser("image/*", PIC_SELECT_CODE);
                break;
            case R.id.bt_share_audio:
                openFileChooser("audio/*", AUDIO_SELECT_CODE);
                break;
            case R.id.bt_share_video:
                openFileChooser("video/*", VIDEO_SELECT_CODE);
                break;
            case R.id.bt_share_file:
                openFileChooser("*/*", FILE_SELECT_CODE);

                break;
            default:
                break;
        }
    }

    private void openFileChooser(String type, int openType) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(type);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "选择文件"), openType);
            overridePendingTransition(0, 0);
        } catch (Exception ex) {
            // Potentially direct the user to the Market with OnProgressChangeListener Dialog
            Toast.makeText(this, "请先安装文件管理器", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("DemoActivity", "requestCode=" + requestCode + " resultCode=" + resultCode);
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            new ShareBySystem.Builder(this)
                    .setContentType(ShareContentType.FILE)
                    .setShareFileUri(uri)
                    .setTitle("Share File")
                    .setOnActivityResult(REQUEST_SHARE_FILE_CODE)
                    .build()
                    .shareBySystem();
        } else if (requestCode == PIC_SELECT_CODE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            new ShareBySystem.Builder(this)
                    .setContentType(ShareContentType.FILE)
                    .setShareFileUri(uri)
                    //.setShareToComponent("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI")
                    .setTitle("Share Image")
                    .build()
                    .shareBySystem();
        } else if (requestCode == AUDIO_SELECT_CODE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            new ShareBySystem.Builder(this)
                    .setContentType(ShareContentType.FILE)
                    .setShareFileUri(uri)
                    //.setShareToComponent("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI")
                    .setTitle("Share Image")
                    .build()
                    .shareBySystem();
        } else if (requestCode == VIDEO_SELECT_CODE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            new ShareBySystem.Builder(this)
                    .setContentType(ShareContentType.FILE)
                    .setShareFileUri(uri)
                    .setTitle("Share Video")
                    .build()
                    .shareBySystem();
        } else if (requestCode == REQUEST_SHARE_FILE_CODE) {

        }
    }

    public Uri getShareFileUri() {
        if (shareFileUrl == null) {
            editText.setText("Please choose a file to share.");
        }
        return shareFileUrl;
    }
}
